from fastapi import APIRouter
from pojo.pojo import *
from dbo.dbutil import *

app = APIRouter()

@app.post("/login")
async def login(user:User):
    rs = {"code":200,'msg':"成功",'data':[]}
    sql = '''
    SELECT * FROM user 
    WHERE userName = '{}' AND password = '{}'
    '''.format(user.userName,user.password)
    data = Mysql().selectDB(sql,'one')
    if data is None:
        rs["code"]=500
        rs["msg"]="登陆失败，用户不存在或密码错误"
        return rs
    rs["data"]=data
    return rs

@app.post("/register")
async def register(user:User):
    rs = {"code":200,'msg':"成功",'data':[]}
    sql = '''
    INSERT INTO user(userName,password,sex,edu,tele,nickName,age)
    VALUES('{}','{}','{}','{}','{}','{}','{}')
    '''.format(user.userName,user.password,user.sex,user.edu,user.tele,user.nickName,user.age)
    print(sql)
    data = Mysql().insertDB(sql)
    if data==0:
        rs["code"]=500
        rs["msg"]="注册失败，程序员紧急处理中"
        return rs
    
    return rs


@app.post("/getUserList")
async def getUserList():
    rs = {"code":200,'msg':"成功",'data':[]}
    sql = '''
    SELECT * FROM user
    '''
    print(sql)
    data = Mysql().selectDB(sql,'many')
    if data is None:
        rs["code"]=500
        rs["msg"]="查询失败，用户不存在或密码错误"
        return rs
    rs["data"]=data
    return rs

@app.post("/updateUserInfo")
async def updateUserInfo(data:User,user:User):
    rs = {"code":200,'msg':"成功",'data':[]}
    sql = '''
    UPDATE user SET userName='{}',password='{}',sex='{}',edu='{}',tele='{}',nickName='{}',age='{}',avatar='{}'
    WHERE id='{}'
    '''.format(data.userName,data.password,data.sex,data.edu,data.tele,data.nickName,data.age,data.avatar,data.id)
    print(sql)
    dataRS = Mysql().insertDB(sql)
    if dataRS==0:
        rs["code"]=500
        rs["msg"]="您的信息未发生变更"
        rs['data']=data
        return rs
    rs['data']=data
    return rs


@app.post("/getUserInfoByID")
async def getUserInfoByID(user:User):
    rs = {"code":200,'msg':"成功",'data':[]}
    sql = '''
    SELECT * FROM user
    WHERE id = '{}'
    '''.format(user.id)
    print(sql)
    data = Mysql().selectDB(sql,'one')
    if data is None:
        rs["code"]=500
        rs["msg"]="查询失败，程序员修复中"
        return rs
    rs["data"]=data
    return rs
